package com.taotao.database.druid;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.taotao.database.mybatis.ReadWriteSplitRoutingDataSource;

/**
 * @author liujian
 *
 */
@Configuration
@AutoConfigureAfter({ DataSourceConfiguration.class })
public class MybatisConfiguration extends MybatisAutoConfiguration {

	private static Log logger = LogFactory.getLog(MybatisConfiguration.class);

	@Resource(name = "masterDataSource")
	private DataSource masterDataSource;
	@Resource(name = "slaveDataSource")
	private DataSource slaveDataSource;

	@Bean
	public SqlSessionFactory sqlSessionFactoryTest(ReadWriteSplitRoutingDataSource dataSource) throws Exception {
		logger.info("-------------------- 重载父类 sqlSessionFactory init---------------------");
		return super.sqlSessionFactory(dataSource);
	}

	@Bean
	public ReadWriteSplitRoutingDataSource roundRobinDataSouceProxy() {
		ReadWriteSplitRoutingDataSource proxy = new ReadWriteSplitRoutingDataSource();
		// Map<Object, Object> targetDataResources = new
		// ClassLoaderRepository.SoftHashMap();
		Map<Object, Object> targetDataResources = new HashMap<Object, Object>();
		targetDataResources.put(ReadWriteSplitRoutingDataSource.DbType.MASTER, masterDataSource);
		targetDataResources.put(ReadWriteSplitRoutingDataSource.DbType.SLAVE, slaveDataSource);
		proxy.setDefaultTargetDataSource(masterDataSource);
		proxy.setTargetDataSources(targetDataResources);

		return proxy;
	}
}
